package com.lakeworks.listener.distribution;

import com.alibaba.fastjson.JSONObject;
import com.lakeworks.common.utils.http.HttpUtils;
import com.lakeworks.domain.OprProduct;
import com.lakeworks.domain.OprShipment;
import com.lakeworks.event.DistributionEvent;
import com.lakeworks.mapper.OprProductMapper;
import com.lakeworks.mapper.OprShipmentMapper;
import com.lakeworks.service.IOprShipmentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;


public class WSListener implements DistributionListener{


    private static final Logger log = LoggerFactory.getLogger(WSListener.class);

    @Autowired
    private OprProductMapper oprProductMapper;

    @Autowired
    private OprShipmentMapper oprShipmentMapper;

    private static final String URL = "https://5y45884w44.goho.co/uploadOrder";



    @EventListener
    public void fenPei(DistributionEvent event) {
        log.info("二次分配线同步数据---event:[{}]",event);
        OprShipment shipment = oprShipmentMapper.queryByChannelIdAndChShipmentNo(event.getChannelId(), event.getShipmentNo());
        if(shipment != null){
            List<OprProduct> products = oprProductMapper.queryByShipmentIdExcludeCompanion(shipment.getId());
            if(!CollectionUtils.isEmpty(products)){
                JSONObject params = new JSONObject();
                params.put("orderCode",shipment.getChShipmentNo());
                params.put("barCode",products.stream().map(OprProduct::getBarcode).mapToLong(Long::valueOf).toArray());
                params.put("number",products.size());
                params.put("timeStamp", String.valueOf(new Date().getTime()));
                try {
                    HttpUtils.postRequest(URL,params.toJSONString());
                } catch (Exception e){
                    log.error("二次分配线同步失败---error:[{}]",e);
                }
            }
        }
    }


}
